unit uFunction;

interface
  uses Windows,Classes,Graphics,uBase64;
function hDIBToTBitmap(CONST hDIB:  THandle):  TBitmap;
function WidestringToString(source:WideString):string;

function Base64Encode(InputData: string; var OutputData: string): byte;
function Base64Decode(InputData: string; var OutputData: string): byte;

implementation

function hDIBToTBitmap(CONST hDIB:  THandle):  TBitmap;
var
    BitCount        :  INTEGER;
    BitmapFileHeader:  TBitmapFileHeader;
    BitmapInfo      :  pBitmapInfo;
    DIBinMemory     :  Pointer;
    MemoryStream    :  TMemoryStream;
    NumberOfColors  :  INTEGER;
begin
  RESULT := TBitmap.Create;

  DIBinMemory := GlobalLock(hDIB);
  try
    BitmapInfo := DIBInMemory;
    NumberOfColors := BitmapInfo.bmiHeader.biClrUsed;
    BitCount       := BitmapInfo.bmiHeader.biBitCount;
    if   (NumberOfColors = 0) and (BitCount <= 8) then
      NumberOfColors := 1 shl BitCount;

    with BitmapFileHeader do
    begin
      bfType := $4D42;  // 'BM'
      bfReserved1 := 0;
      bfReserved2 := 0;
      bfOffBits := SizeOf(TBitmapFileHeader)       +
                   SizeOf(TBitmapInfoHeader)       +
                   NumberOfColors*SizeOf(TRGBQuad);
      bfSize := bfOffBits + BitmapInfo.bmiHeader.biSizeImage;
    end;

    MemoryStream := TMemoryStream.Create;
    try
      MemoryStream.Write(BitmapFileHeader, SizeOf(TBitmapFileHeader));
      MemoryStream.Write(DIBInMemory^,
                         BitmapFileHeader.bfSize - SizeOf(TBitmapFileHeader));
      MemoryStream.Position := 0;
      RESULT.LoadFromStream(MemoryStream)
    finally
      MemoryStream.Free
    end;

  finally
    GlobalUnlock(hDIB);
    //GlobalFree(hDIB)
  end;
end;


function WidestringToString(source:WideString):string;
var
  Len: Integer;
begin
  Len := WideCharToMultiByte(936,0,PWideChar(source),-1,nil,0,nil,nil);
  SetLength(Result,Len-1);
  WideCharToMultiByte(936,0,PWideChar(source),Length(source),PChar(Result),Len-1,nil,nil);
end;

function Base64Encode(InputData: string; var OutputData: string): byte;
begin
  Result:=uBase64.Base64Encode(InputData,OutputData);
end;

function Base64Decode(InputData: string; var OutputData: string): byte;
begin
  Result:=uBase64.Base64Decode(InputData,OutputData);
end;

end.
